package com.zeus.core.open.aspect;

import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.open.api.annotation.ZeusAlarmAop;
import com.zeus.core.report.ZeusReportAnnotationClient;
import com.zeus.core.report.ZeusReportClient;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 宙斯告警切面
 *
 * @author wangfeixiong126@gmail.com  2021/6/22 02:17
 */
@Aspect
public class ZeusAlarmAspect {
    private final static Logger logger = LoggerFactory.getLogger(ZeusAlarmAspect.class);

    /**
     * zeusAlarm
     *
     * @author wangfeixiong126@gmail.com  2021/6/22 18:44
     */
    @Pointcut("@annotation(com.zeus.core.open.api.annotation.ZeusAlarmAop)")
    private void zeusAlarm() {

    }

    /**
     * 切面监控告警
     * 
     * @param point point
     * @param alarm alarm
     * @return Object
     * @author wangfeixiong126@gmail.com  2021/6/22 18:43
     */
    @Around("zeusAlarm() && @annotation(alarm)")
    public Object zeusMonitorAlarm(ProceedingJoinPoint point, ZeusAlarmAop alarm) throws Throwable {
        Object resultData;
        try {
            resultData = point.proceed();
        } catch (Throwable throwable) {
            // 进行告警
            alarmAnnotation(point, alarm, throwable);
            throw throwable;
        }
        return resultData;
    }

    /**
     * 注解报警
     * 
     * @param point point
     * @param alarm alarm
     * @author wangfeixiong126@gmail.com  2021/6/23 11:50
     */
    private void alarmAnnotation(ProceedingJoinPoint point, ZeusAlarmAop alarm, Throwable throwable) {
        try {
            ZeusReportClient client = new ZeusReportAnnotationClient(point, alarm, throwable);
            client.complete();
        } catch (Throwable t) {
            if (logger.isWarnEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                logger.warn("### Zeus监控服务, 切面加工告警信息失败 >> errMsg = {}", t.getMessage());
            }
        }
    }
}
